// gulp 的入口文件

// 1.导出函数成员的方式，使用异步回调
exports.foo = done => {
    console.log('foo task')
    done()
}

exports.default = done => {
    console.log('default task')
}

// 不推荐
const gulp = require('gulp')
gulp.task('bar', done => {
    console.log('bar task')
    done()
})
// ---------------------------------

// 2.组合任务，并行和串行

const { series, parallel } = require('gulp')

const task1 = done => {
    setTimeout(() => {
        console.log('task1 ~')
        done()
    }, 1000);
}
const task2 = done => {
    setTimeout(() => {
        console.log('task2 ~')
        done()
    }, 1000);
}
const task3 = done => {
    setTimeout(() => {
        console.log('task2 ~')
        done()
    }, 1000);
}

exports.seriesTask = series(task1, task2, task3) //串行，依次执行
exports.parallelTask = parallel(task1, task2, task3) //并行，同时执行，互不影响

// ------------------------------------------

// 3.异步任务：回调，promise，async/await,stream
exports.asyncTask1 = done => {
    console.log('asyncTask1')
    done()
}

exports.asyncTask2 = () => {
    console.log('asyncTask2')
    return Promise.resolve()
    return Promise.reject(new Error('task failed'))
}

const timeout = time => {
    return new Promise(resolve => {
        setTimeout(resolve, time);
    })
}
exports.asyncTask3 = async () => {
    await timeout(1000)
    console.log('asyncTask3')
}

// ------------------------------------

// 4.核心工作原理：读取流，转换流，写入流
const fs = require('fs')
const { Transform } = require('stream')

exports.fileTask = () => {
    //文件读取流
    const read = fs.createReadStream('main.css')
    //文件写入流
    const output = fs.createWriteStream('main.min.css')
    // 文件转换流
    const transform = new Transform({
        transform: (chunk, encoding, callback) => {
            //核心转换过程实现
            // chunk =》 读取流中读取到的数据（Buffer）
            const input = chunk.toString()
            const output = input.replace(/\s+/g, '').replace(/\/\*.+?\*\//g, '')
            callback(null, output)
        }
    })

    //把读取出来的数据经过转换写入文件流
    read.pipe(transform)
        .pipe(output)

    return read
}

// ----------------------------------------
// 5.文件操作api：src,dest + 插件

const { src, dest } = require('gulp')
const cleanCss = require('gulp-clean-css')
const rename = require('gulp-rename')

exports.fileTask2 = () => {
    return src('css/*.css')
    .pipe(cleanCss())
    .pipe(rename({extname:'.min.css'}))
    .pipe(dest('dist'))
}

